#include "clientwindow.h"
#include <QSettings>
#include <QApplication>
#include <QScreen>
#include <QStyle>
#include <QGuiApplication>
#include <QActionGroup>
#include <QFileDialog>
#include <QProgressDialog>

ClientWindow::ClientWindow(QWidget *parent)
    : QMainWindow(parent),
      frameCount(0),
      lanDiscoveryActive(false)
{
    // 创建客户端对象
    client = new Client(this);
    
    // 创建刷新定时器
    refreshTimer = new QTimer(this);
    connect(refreshTimer, &QTimer::timeout, this, &ClientWindow::onRequestScreenUpdate);
    
    // 创建FPS统计定时器
    fpsTimer = new QTimer(this);
    connect(fpsTimer, &QTimer::timeout, this, &ClientWindow::updateFpsDisplay);
    fpsTimer->start(1000);  // 每秒更新一次
    
    // 获取局域网发现服务
    lanService = LANService::getInstance();
    
    connect(lanService, &LANService::serverDiscovered, 
            this, &ClientWindow::onServerDiscovered);
    
    connect(lanService, &LANService::serverLost, 
            this, &ClientWindow::onServerLost);
    
    // 连接客户端信号
    connect(client, &Client::connectionStatusChanged, 
            this, &ClientWindow::onConnectionStatusChanged);
    
    connect(client, &Client::authenticationResult, 
            this, &ClientWindow::onAuthenticationResult);
    
    connect(client, &Client::screenDataUpdated, 
            this, &ClientWindow::onScreenDataUpdated);
    
    connect(client, &Client::errorOccurred, 
            this, &ClientWindow::onErrorOccurred);
    
    // 设置窗口属性
    setWindowTitle("Hand-in-Hand 客户端");
    resize(1024, 768);
    
    // 创建UI
    setupUi();
    
    // 创建菜单
    createMenus();
    
    // 加载设置
    loadSettings();
    
    LOG_INFO("客户端窗口初始化完成");
}

ClientWindow::~ClientWindow()
{
    LOG_INFO("客户端窗口销毁");
    
    // 释放文件传输进度对话框
    if (fileTransferProgress) {
        fileTransferProgress->close();
        delete fileTransferProgress;
        fileTransferProgress = nullptr;
    }
    
    // 保存设置
    saveSettings();
    
    // 停止定时器
    refreshTimer->stop();
    fpsTimer->stop();
    
    // 停止局域网发现
    if (lanDiscoveryActive) {
        lanService->stopClientDiscovery();
    }
    
    // 断开连接
    if (client->isConnected()) {
        client->disconnectFromServer();
    }
}

bool ClientWindow::connectToServer(const QString &host, quint16 port)
{
    hostEdit->setText(host);
    portSpinBox->setValue(port);
    
    onConnectButtonClicked();
    return client->isConnected();
}

void ClientWindow::closeEvent(QCloseEvent *event)
{
    LOG_INFO("客户端窗口关闭");
    
    // 保存设置
    saveSettings();
    
    // 停止定时器
    refreshTimer->stop();
    fpsTimer->stop();
    
    // 停止局域网发现
    if (lanDiscoveryActive) {
        lanService->stopClientDiscovery();
    }
    
    // 断开连接
    if (client->isConnected()) {
        client->disconnectFromServer();
    }
    
    event->accept();
}

void ClientWindow::onConnectButtonClicked()
{
    // 如果已经连接，不要重复连接
    if (client->isConnected()) {
        QMessageBox::information(this, "连接提示", "已经连接到服务器，请先断开当前连接");
        return;
    }
    
    QString host = hostEdit->text().trimmed();
    quint16 port = portSpinBox->value();
    
    if (host.isEmpty()) {
        QMessageBox::warning(this, "连接错误", "请输入服务器地址");
        return;
    }
    
    LOG_INFO(QString("尝试连接到服务器: %1:%2").arg(host).arg(port));
    
    // 禁用连接按钮
    connectButton->setEnabled(false);
    
    // 更新状态栏
    connectionStatusLabel->setText("正在连接...");
    
    // 连接到服务器
    client->connectToServer(host, port);
}

void ClientWindow::onDisconnectButtonClicked()
{
    // 停止刷新定时器
    refreshTimer->stop();
    
    // 断开连接
    client->disconnectFromServer();
}

void ClientWindow::onConnectionStatusChanged(bool connected)
{
    connectButton->setEnabled(!connected);
    disconnectButton->setEnabled(connected);
    
    authWidget->setEnabled(connected);
    
    // 控制部分初始状态禁用，需要认证后启用
    controlWidget->setEnabled(false);
    
    // 在连接状态变化时更新屏幕控制状态
    screenViewer->setControlEnabled(false); // 初始状态禁用，认证成功后再启用
    
    // 清空屏幕显示
    if (!connected) {
        screenViewer->setImage(QByteArray());
    }
    
    // 更新状态栏
    connectionStatusLabel->setText(connected ? "已连接" : "未连接");
    serverInfoLabel->setText(connected ? 
                            QString("%1:%2").arg(hostEdit->text()).arg(portSpinBox->value()) : 
                            "");
    
    // 设置窗口标题
    setWindowTitle(QString("Hand-in-Hand 客户端 - %1").arg(connected ? 
                          QString("已连接到 %1:%2").arg(hostEdit->text()).arg(portSpinBox->value()) : 
                          "未连接"));
    
    updateStatusBar();
}

void ClientWindow::onAuthenticateButtonClicked()
{
    QString username = usernameEdit->text().trimmed();
    QString password = passwordEdit->text();
    
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "认证错误", "请输入用户名和密码");
        return;
    }
    
    LOG_INFO(QString("发送认证请求: %1").arg(username));
    
    // 禁用认证按钮
    authButton->setEnabled(false);
    
    // 发送认证请求
    client->authenticate(username, password);
}

void ClientWindow::onAuthenticationResult(bool success, const QString &message)
{
    authButton->setEnabled(true);
    
    if (success) {
        LOG_INFO("认证成功");
        
        // 启用控制部分
        controlWidget->setEnabled(true);
        
        // 确保启用屏幕控制
        screenViewer->setControlEnabled(true);
        screenViewer->setFocus(); // 让屏幕查看器获取焦点以接收键盘事件
        
        // 请求屏幕数据
        onRequestScreenUpdate();
        
        // 如果启用了自动刷新，则启动定时器
        if (autoRefreshCheckBox->isChecked()) {
            int interval = 1000 / refreshRateSpinBox->value();
            refreshTimer->start(interval);
        }
        
        // 更新状态栏
        connectionStatusLabel->setText(QString("已认证: %1").arg(usernameEdit->text()));
        
        // 隐藏密码
        passwordEdit->clear();
    } else {
        LOG_WARNING(QString("认证失败: %1").arg(message));
        
        // 禁用屏幕控制
        screenViewer->setControlEnabled(false);
        
        // 显示错误消息
        QMessageBox::warning(this, "认证失败", message);
    }
    
    updateStatusBar();
}

void ClientWindow::onScreenDataUpdated(const QByteArray &imageData, int width, int height)
{
    // 更新屏幕显示
    screenViewer->setImage(imageData);
    
    // 设置远程屏幕尺寸
    screenViewer->setRemoteScreenSize(width, height);
    
    // 增加帧计数
    frameCount++;
    
    // 更新状态栏
    serverInfoLabel->setText(QString("%1:%2 (%3x%4)")
                            .arg(hostEdit->text())
                            .arg(portSpinBox->value())
                            .arg(width)
                            .arg(height));
    
    updateStatusBar();
}

void ClientWindow::onMousePressed(int x, int y, int button)
{
    if (!client->isConnected()) {
        return;
    }
    
    client->sendMouseEvent(x, y, button, true);
}

void ClientWindow::onMouseReleased(int x, int y, int button)
{
    if (!client->isConnected()) {
        return;
    }
    
    client->sendMouseEvent(x, y, button, false);
}

void ClientWindow::onMouseMoved(int x, int y)
{
    if (!client->isConnected()) {
        return;
    }
    
    client->sendMouseEvent(x, y, 0, false);
}

void ClientWindow::onKeyPressed(int key)
{
    if (!client->isConnected()) {
        return;
    }
    
    client->sendKeyboardEvent(key, true);
}

void ClientWindow::onKeyReleased(int key)
{
    if (!client->isConnected()) {
        return;
    }
    
    client->sendKeyboardEvent(key, false);
}

void ClientWindow::onRefreshRateChanged(int fps)
{
    if (fps <= 0) {
        refreshTimer->stop();
        return;
    }
    
    // 计算刷新间隔
    int interval = 1000 / fps;
    
    // 如果定时器正在运行，则更新间隔
    if (refreshTimer->isActive()) {
        refreshTimer->setInterval(interval);
    }
    
    LOG_INFO(QString("刷新率已设置为 %1 FPS (间隔 %2 ms)").arg(fps).arg(interval));
}

void ClientWindow::onAutoRefreshToggled(bool enabled)
{
    if (enabled && client->isConnected()) {
        int interval = 1000 / refreshRateSpinBox->value();
        refreshTimer->start(interval);
        LOG_INFO(QString("自动刷新已启用，间隔 %1 ms").arg(interval));
    } else {
        refreshTimer->stop();
        LOG_INFO("自动刷新已禁用");
    }
    
    // 更新刷新按钮状态
    refreshButton->setEnabled(!enabled);
}

void ClientWindow::onRequestScreenUpdate()
{
    if (client->isConnected()) {
        client->requestScreenData();
    }
}

void ClientWindow::onScaleModeChanged(int index)
{
    ScreenViewer::ScaleMode mode;
    
    switch (index) {
    case 0:
        mode = ScreenViewer::NoScale;
        break;
    case 1:
        mode = ScreenViewer::ScaleToFit;
        break;
    case 2:
        mode = ScreenViewer::ScaleKeepRatio;
        break;
    default:
        mode = ScreenViewer::ScaleKeepRatio;
        break;
    }
    
    screenViewer->setScaleMode(mode);
}

void ClientWindow::onErrorOccurred(const QString &errorMsg)
{
    LOG_ERROR(QString("错误: %1").arg(errorMsg));
    
    // 显示错误消息
    QMessageBox::critical(this, "错误", errorMsg);
    
    // 如果是在连接过程中发生错误，重新启用连接按钮
    if (!client->isConnected()) {
        connectButton->setEnabled(true);
    }
}

void ClientWindow::setupUi()
{
    // 创建中央窗口部件
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    
    // 主布局
    mainLayout = new QVBoxLayout(centralWidget);
    
    // 创建分割器
    QSplitter *splitter = new QSplitter(Qt::Horizontal, centralWidget);
    mainLayout->addWidget(splitter);
    
    // 左侧面板 - 控制和设置
    QWidget *leftPanel = new QWidget(splitter);
    QVBoxLayout *leftLayout = new QVBoxLayout(leftPanel);
    
    // 连接部分
    QGroupBox *connectionGroup = new QGroupBox("连接", leftPanel);
    QVBoxLayout *connectionGroupLayout = new QVBoxLayout(connectionGroup);
    
    connectionWidget = new QWidget(connectionGroup);
    connectionLayout = new QHBoxLayout(connectionWidget);
    
    hostLabel = new QLabel("主机:", connectionWidget);
    connectionLayout->addWidget(hostLabel);
    
    hostEdit = new QLineEdit(connectionWidget);
    hostEdit->setText("localhost");
    connectionLayout->addWidget(hostEdit);
    
    portLabel = new QLabel("端口:", connectionWidget);
    connectionLayout->addWidget(portLabel);
    
    portSpinBox = new QSpinBox(connectionWidget);
    portSpinBox->setRange(1, 65535);
    portSpinBox->setValue(5900);
    connectionLayout->addWidget(portSpinBox);
    
    connectButton = new QPushButton("连接", connectionWidget);
    connect(connectButton, &QPushButton::clicked, this, &ClientWindow::onConnectButtonClicked);
    connectionLayout->addWidget(connectButton);
    
    disconnectButton = new QPushButton("断开", connectionWidget);
    connect(disconnectButton, &QPushButton::clicked, this, &ClientWindow::onDisconnectButtonClicked);
    connectionLayout->addWidget(disconnectButton);
    
    connectionGroupLayout->addWidget(connectionWidget);
    leftLayout->addWidget(connectionGroup);
    
    // 添加局域网发现部分
    lanGroup = new QGroupBox("局域网服务器", leftPanel);
    lanLayout = new QVBoxLayout(lanGroup);
    
    lanServerList = new QListWidget(lanGroup);
    lanServerList->addItem("未发现局域网服务器");
    connect(lanServerList, &QListWidget::itemDoubleClicked, this, &ClientWindow::onLANServerSelected);
    lanLayout->addWidget(lanServerList);
    
    lanButtonLayout = new QHBoxLayout();
    
    refreshLANButton = new QPushButton("刷新", lanGroup);
    connect(refreshLANButton, &QPushButton::clicked, this, &ClientWindow::onRefreshLANServers);
    lanButtonLayout->addWidget(refreshLANButton);
    
    connectLANButton = new QPushButton("连接", lanGroup);
    connect(connectLANButton, &QPushButton::clicked, [this]() {
        if (lanServerList->currentItem()) {
            onLANServerSelected(lanServerList->currentItem());
        }
    });
    lanButtonLayout->addWidget(connectLANButton);
    
    lanLayout->addLayout(lanButtonLayout);
    leftLayout->addWidget(lanGroup);
    
    // 认证部分
    QGroupBox *authGroup = new QGroupBox("认证", leftPanel);
    QVBoxLayout *authGroupLayout = new QVBoxLayout(authGroup);
    
    authWidget = new QWidget(authGroup);
    authLayout = new QHBoxLayout(authWidget);
    
    usernameLabel = new QLabel("用户名:", authWidget);
    authLayout->addWidget(usernameLabel);
    
    usernameEdit = new QLineEdit(authWidget);
    usernameEdit->setText("admin");
    authLayout->addWidget(usernameEdit);
    
    passwordLabel = new QLabel("密码:", authWidget);
    authLayout->addWidget(passwordLabel);
    
    passwordEdit = new QLineEdit(authWidget);
    passwordEdit->setEchoMode(QLineEdit::Password);
    authLayout->addWidget(passwordEdit);
    
    authButton = new QPushButton("认证", authWidget);
    connect(authButton, &QPushButton::clicked, this, &ClientWindow::onAuthenticateButtonClicked);
    authLayout->addWidget(authButton);
    
    authGroupLayout->addWidget(authWidget);
    leftLayout->addWidget(authGroup);
    
    // 控制部分
    QGroupBox *controlGroup = new QGroupBox("控制", leftPanel);
    QVBoxLayout *controlGroupLayout = new QVBoxLayout(controlGroup);
    
    controlWidget = new QWidget(controlGroup);
    controlLayout = new QHBoxLayout(controlWidget);
    
    refreshRateLabel = new QLabel("刷新率:", controlWidget);
    controlLayout->addWidget(refreshRateLabel);
    
    refreshRateSpinBox = new QSpinBox(controlWidget);
    refreshRateSpinBox->setRange(1, 60);
    refreshRateSpinBox->setValue(10);
    connect(refreshRateSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), 
            this, &ClientWindow::onRefreshRateChanged);
    controlLayout->addWidget(refreshRateSpinBox);
    
    autoRefreshCheckBox = new QCheckBox("自动刷新", controlWidget);
    autoRefreshCheckBox->setChecked(true);
    connect(autoRefreshCheckBox, &QCheckBox::toggled, 
            this, &ClientWindow::onAutoRefreshToggled);
    controlLayout->addWidget(autoRefreshCheckBox);
    
    scaleModeLabel = new QLabel("缩放模式:", controlWidget);
    controlLayout->addWidget(scaleModeLabel);
    
    scaleModeComboBox = new QComboBox(controlWidget);
    scaleModeComboBox->addItem("拉伸适应窗口");
    scaleModeComboBox->addItem("保持纵横比");
    scaleModeComboBox->addItem("原始大小");
    connect(scaleModeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &ClientWindow::onScaleModeChanged);
    controlLayout->addWidget(scaleModeComboBox);
    
    refreshButton = new QPushButton("刷新", controlWidget);
    connect(refreshButton, &QPushButton::clicked, 
            this, &ClientWindow::onRequestScreenUpdate);
    controlLayout->addWidget(refreshButton);
    
    controlLayout->addStretch();
    
    controlGroupLayout->addWidget(controlWidget);
    leftLayout->addWidget(controlGroup);
    
    // 添加伸展空间以保持布局美观
    leftLayout->addStretch();
    
    // 左侧面板添加到分割器
    splitter->addWidget(leftPanel);
    
    // 右侧 - 屏幕查看器
    screenViewer = new ScreenViewer();
    splitter->addWidget(screenViewer);
    
    // 连接屏幕查看器信号到槽函数
    connect(screenViewer, &ScreenViewer::mousePressed, this, &ClientWindow::onMousePressed);
    connect(screenViewer, &ScreenViewer::mouseReleased, this, &ClientWindow::onMouseReleased);
    connect(screenViewer, &ScreenViewer::mouseMoved, this, &ClientWindow::onMouseMoved);
    connect(screenViewer, &ScreenViewer::keyPressed, this, &ClientWindow::onKeyPressed);
    connect(screenViewer, &ScreenViewer::keyReleased, this, &ClientWindow::onKeyReleased);
    
    // 设置分割器初始大小
    splitter->setSizes(QList<int>() << 300 << 700);
    
    // 创建状态栏
    statusBar();
    
    connectionStatusLabel = new QLabel("未连接");
    statusBar()->addWidget(connectionStatusLabel);
    
    serverInfoLabel = new QLabel("");
    statusBar()->addWidget(serverInfoLabel);
    
    fpsLabel = new QLabel("0 FPS");
    statusBar()->addPermanentWidget(fpsLabel);
    
    // 设置初始状态
    disconnectButton->setEnabled(false);
    authWidget->setEnabled(false);
    controlWidget->setEnabled(false);
    
    // 设置屏幕查看器为焦点
    screenViewer->setFocus();
    
    // 将窗口移动到屏幕中央
    QScreen *screen = QGuiApplication::primaryScreen();
    setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), screen->availableGeometry()));
}

void ClientWindow::createMenus()
{
    // 创建主菜单
    QMenu *fileMenu = menuBar()->addMenu("文件");
    
    QAction *connectAction = new QAction("连接...", this);
    connect(connectAction, &QAction::triggered, 
            this, &ClientWindow::onConnectButtonClicked);
    fileMenu->addAction(connectAction);
    
    QAction *disconnectAction = new QAction("断开连接", this);
    connect(disconnectAction, &QAction::triggered, 
            this, &ClientWindow::onDisconnectButtonClicked);
    fileMenu->addAction(disconnectAction);
    
    // 文件传输相关
    QAction *sendFileAction = new QAction("发送文件", this);
    connect(sendFileAction, &QAction::triggered, this, &ClientWindow::onSendFileAction);
    fileMenu->addAction(sendFileAction);

    QAction *receiveFileAction = new QAction("接收文件", this);
    connect(receiveFileAction, &QAction::triggered, this, &ClientWindow::onReceiveFileAction);
    fileMenu->addAction(receiveFileAction);
    
    fileMenu->addSeparator();
    
    QAction *exitAction = new QAction("退出", this);
    connect(exitAction, &QAction::triggered, this, &QWidget::close);
    fileMenu->addAction(exitAction);
    
    // 创建视图菜单
    QMenu *viewMenu = menuBar()->addMenu("视图(&V)");
    
    QAction *refreshAction = viewMenu->addAction("刷新(&R)");
    refreshAction->setShortcut(QKeySequence("F5"));
    connect(refreshAction, &QAction::triggered, this, &ClientWindow::onRequestScreenUpdate);
    
    QAction *autoRefreshAction = viewMenu->addAction("自动刷新(&A)");
    autoRefreshAction->setCheckable(true);
    autoRefreshAction->setChecked(true);
    connect(autoRefreshAction, &QAction::toggled, this, &ClientWindow::onAutoRefreshToggled);
    connect(autoRefreshCheckBox, &QCheckBox::toggled, autoRefreshAction, &QAction::setChecked);
    
    viewMenu->addSeparator();
    
    QMenu *scaleModeMenu = viewMenu->addMenu("缩放模式(&S)");
    
    QAction *noScaleAction = scaleModeMenu->addAction("原始大小(&O)");
    noScaleAction->setCheckable(true);
    
    QAction *scaleToFitAction = scaleModeMenu->addAction("适应窗口(&F)");
    scaleToFitAction->setCheckable(true);
    
    QAction *scaleKeepRatioAction = scaleModeMenu->addAction("保持比例(&K)");
    scaleKeepRatioAction->setCheckable(true);
    scaleKeepRatioAction->setChecked(true);
    
    QActionGroup *scaleModeGroup = new QActionGroup(this);
    scaleModeGroup->addAction(noScaleAction);
    scaleModeGroup->addAction(scaleToFitAction);
    scaleModeGroup->addAction(scaleKeepRatioAction);
    
    connect(noScaleAction, &QAction::triggered, [this]() {
        scaleModeComboBox->setCurrentIndex(0);
    });
    connect(scaleToFitAction, &QAction::triggered, [this]() {
        scaleModeComboBox->setCurrentIndex(1);
    });
    connect(scaleKeepRatioAction, &QAction::triggered, [this]() {
        scaleModeComboBox->setCurrentIndex(2);
    });
    
    // 创建帮助菜单
    QMenu *helpMenu = menuBar()->addMenu("帮助(&H)");
    
    QAction *aboutAction = helpMenu->addAction("关于(&A)");
    connect(aboutAction, &QAction::triggered, [this]() {
        QMessageBox::about(this, "关于 Hand-in-Hand 客户端",
                          "Hand-in-Hand 远程桌面控制软件\n"
                          "版本: 1.0.0\n"
                          "客户端模式\n\n"
                          "基于Qt 5.11.3开发");
    });
}

void ClientWindow::updateStatusBar()
{
    statusBar()->showMessage("");
}

void ClientWindow::updateFpsDisplay()
{
    fpsLabel->setText(QString("%1 FPS").arg(frameCount));
    frameCount = 0;
}

void ClientWindow::loadSettings()
{
    QSettings settings("Hand-in-Hand", "Client");
    
    // 读取服务器设置
    hostEdit->setText(settings.value("connection/host", "localhost").toString());
    portSpinBox->setValue(settings.value("connection/port", 5900).toInt());
    
    // 读取用户名
    usernameEdit->setText(settings.value("auth/username", "admin").toString());
    
    // 读取刷新率
    refreshRateSpinBox->setValue(settings.value("view/refreshRate", 10).toInt());
    
    // 读取自动刷新
    bool autoRefresh = settings.value("view/autoRefresh", true).toBool();
    autoRefreshCheckBox->setChecked(autoRefresh);
    
    // 读取缩放模式
    int scaleMode = settings.value("view/scaleMode", 2).toInt();
    scaleModeComboBox->setCurrentIndex(scaleMode);
    onScaleModeChanged(scaleMode);
    
    // 读取窗口大小和位置
    if (settings.contains("window/size")) {
        resize(settings.value("window/size").toSize());
    }
    
    if (settings.contains("window/pos")) {
        move(settings.value("window/pos").toPoint());
    }
}

void ClientWindow::saveSettings()
{
    QSettings settings("Hand-in-Hand", "Client");
    
    // 保存服务器设置
    settings.setValue("connection/host", hostEdit->text());
    settings.setValue("connection/port", portSpinBox->value());
    
    // 保存用户名
    settings.setValue("auth/username", usernameEdit->text());
    
    // 保存刷新率
    settings.setValue("view/refreshRate", refreshRateSpinBox->value());
    
    // 保存自动刷新
    settings.setValue("view/autoRefresh", autoRefreshCheckBox->isChecked());
    
    // 保存缩放模式
    settings.setValue("view/scaleMode", scaleModeComboBox->currentIndex());
    
    // 保存窗口大小和位置
    settings.setValue("window/size", size());
    settings.setValue("window/pos", pos());
}

void ClientWindow::onStartLANDiscovery()
{
    if (lanDiscoveryActive) {
        return;
    }
    
    if (lanService->startClientDiscovery()) {
        lanDiscoveryActive = true;
        LOG_INFO("已启动局域网服务器发现");
        
        // 更新界面
        lanServerList->clear();
        lanServerList->addItem("正在搜索局域网服务器...");
        refreshLANButton->setText("停止搜索");
        disconnect(refreshLANButton, &QPushButton::clicked, this, &ClientWindow::onRefreshLANServers);
        connect(refreshLANButton, &QPushButton::clicked, this, &ClientWindow::onStopLANDiscovery);
    } else {
        LOG_ERROR("无法启动局域网服务器发现");
    }
}

void ClientWindow::onStopLANDiscovery()
{
    if (!lanDiscoveryActive) {
        return;
    }
    
    lanService->stopClientDiscovery();
    lanDiscoveryActive = false;
    LOG_INFO("已停止局域网服务器发现");
    
    // 更新界面
    refreshLANButton->setText("刷新");
    disconnect(refreshLANButton, &QPushButton::clicked, this, &ClientWindow::onStopLANDiscovery);
    connect(refreshLANButton, &QPushButton::clicked, this, &ClientWindow::onRefreshLANServers);
}

void ClientWindow::onServerDiscovered(const QString &serverAddress, quint16 serverPort, const QString &serverName)
{
    // 查找是否已经在列表中
    for (int i = 0; i < lanServerList->count(); i++) {
        QListWidgetItem *item = lanServerList->item(i);
        if (item->data(Qt::UserRole).toString() == serverAddress) {
            // 更新现有项
            QString displayText = QString("%1 (%2:%3)").arg(serverName).arg(serverAddress).arg(serverPort);
            item->setText(displayText);
            item->setData(Qt::UserRole + 1, serverPort);
            item->setData(Qt::UserRole + 2, serverName);
            return;
        }
    }
    
    // 清除"正在搜索"的项
    if (lanServerList->count() == 1 && lanServerList->item(0)->data(Qt::UserRole).isNull()) {
        lanServerList->clear();
    }
    
    // 添加新项
    QString displayText = QString("%1 (%2:%3)").arg(serverName).arg(serverAddress).arg(serverPort);
    QListWidgetItem *item = new QListWidgetItem(displayText, lanServerList);
    item->setData(Qt::UserRole, serverAddress);  // 存储IP地址
    item->setData(Qt::UserRole + 1, serverPort); // 存储端口
    item->setData(Qt::UserRole + 2, serverName); // 存储服务器名称
}

void ClientWindow::onServerLost(const QString &serverAddress, quint16 /*serverPort*/)
{
    // 从列表中移除
    for (int i = 0; i < lanServerList->count(); i++) {
        QListWidgetItem *item = lanServerList->item(i);
        if (item->data(Qt::UserRole).toString() == serverAddress) {
            delete lanServerList->takeItem(i);
            break;
        }
    }
    
    // 如果列表为空，显示提示
    if (lanServerList->count() == 0) {
        lanServerList->addItem("未发现局域网服务器");
    }
}

void ClientWindow::onLANServerSelected(QListWidgetItem *item)
{
    if (!item || item->data(Qt::UserRole).isNull()) {
        return;
    }
    
    QString serverAddress = item->data(Qt::UserRole).toString();
    quint16 serverPort = item->data(Qt::UserRole + 1).toInt();
    
    // 更新手动连接的字段
    hostEdit->setText(serverAddress);
    portSpinBox->setValue(serverPort);
    
    // 连接到服务器
    onConnectButtonClicked();
}

void ClientWindow::onRefreshLANServers()
{
    // 停止当前发现服务
    onStopLANDiscovery();
    
    // 启动新的发现服务
    onStartLANDiscovery();
}

// 文件传输相关槽函数
void ClientWindow::onSendFileAction()
{
    QString filePath = QFileDialog::getOpenFileName(this, "选择要发送的文件");
    if (!filePath.isEmpty()) {
        // 确保之前的进度对话框已关闭
        if (fileTransferProgress) {
            fileTransferProgress->close();
            delete fileTransferProgress;
        }
        
        // 重新创建新的进度对话框
        fileTransferProgress = new QProgressDialog("正在发送文件...", "取消", 0, 100, this);
        fileTransferProgress->setWindowModality(Qt::WindowModal);
        fileTransferProgress->setMinimumDuration(0);
        
        // 重新连接信号
        disconnect(client, &Client::fileSendProgress, this, nullptr);
        disconnect(client, &Client::fileSendFinished, this, nullptr);
        
        connect(client, &Client::fileSendProgress, this, [this](qint64 sent, qint64 total) {
            if (fileTransferProgress && total > 0) {
                fileTransferProgress->setValue(int(sent * 100 / total));
            }
        });
        
        connect(client, &Client::fileSendFinished, this, [this](bool success, const QString &msg) {
            if (fileTransferProgress) {
                fileTransferProgress->close();
            }
            QMessageBox::information(this, success ? "发送成功" : "发送失败", msg);
        });
        
        client->sendFile(filePath);
    }
}

void ClientWindow::onReceiveFileAction()
{
    QString savePath = QFileDialog::getSaveFileName(this, "选择保存位置");
    if (!savePath.isEmpty()) {
        QMessageBox::information(this, "接收文件", QString("已选择保存路径: %1\n(此处可实现实际接收)").arg(savePath));
        // TODO: 实现文件接收逻辑
    }
} 